<!-- BMS控制 -->
<template>
  <div class="locationIndexPage">
    <div class="menu-container ">
      <div class="custom-wrapper warp">
        <div class="titles">
          运营商
        </div>
        <div style="padding: 15px;">
          <dept-tree v-model="queryParams.customerId" @node-click="handleNodeClick" :currentNodeKey="clientID" />
        </div>
      </div>
      <div class="device-wrapper warp">
        <div class="serach">
          <el-input style="max-width: 180px" v-model="queryParams.deviceCode" placeholder="请输入设备号码"
            class="input-with-select">
            <template #append>
              <el-button icon="search" @click="gpsPage" />
            </template>
          </el-input>
          <el-dropdown trigger="click" style="margin-right: 15px;" popper-class="sortingLocation"
            @command="handleCommand" @click="handleCommand">
            <span class="el-dropdown-link">
              <el-icon>
                <Top />
              </el-icon>
              排序
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="1"><span style="color: #333;">按速度</span></el-dropdown-item>
                <el-dropdown-item command="2"><span style="color: #333;">按静止</span></el-dropdown-item>
                <el-dropdown-item command="3"><span style="color: #333;">按名称</span></el-dropdown-item>
                <el-dropdown-item command="4"><span style="color: #333;">原排序</span></el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="sorting" v-loading="loading">
          <div class="live-title">
            <div class="title-item" @click="menuSelect('ALL')" :class="deptId === 'ALL' ? 'active' : ''">
              全部<br>({{ dataMy.countInfo.total }})
            </div>
            <div class="title-item" @click="menuSelect('ONLINE')" :class="deptId === 'ONLINE' ? 'active' : ''">
              在线<br>({{ dataMy.countInfo.online }})
            </div>
            <div class="title-item" @click="menuSelect('OFFLINE')" :class="deptId === 'OFFLINE' ? 'active' : ''">
              离线<br>({{ dataMy.countInfo.offline }})
            </div>
            <div class="title-item" @click="menuSelect('NOT_ENABLED')"
              :class="deptId === 'NOT_ENABLED' ? 'active' : ''">
              未启用<br>({{ dataMy.countInfo.notEnable }})
            </div>
            <div class="title-item" @click="menuSelect('NOT_EXPIRED')"
              :class="deptId === 'NOT_EXPIRED' ? 'active' : ''">
              未到期<br>({{ dataMy.countInfo.notExpire }})
            </div>
            <div class="title-item" @click="menuSelect('EXPIRED')" :class="deptId === 'EXPIRED' ? 'active' : ''">
              已过期<br>({{ dataMy.countInfo.scrap }})
            </div>
          </div>
          <div class="myTable">
            <div class="flexBetCenter" v-for="(val, idx) in dataMy.data.records" :key="idx" @click="gpsData(val)"
              :class="recordsID === val.id ? 'active' : ''">
              <div>{{ val.deviceCode }}</div>
              <div>{{ val.deviceStatus === 'NOT_ENABLED' ? '未启用' : '' }}</div>
            </div>

          </div>
          <!-- <pagination @pagination="gpsPage" size="small"  layout="sizes, prev, pager, next" v-model:total="queryParams.pages.total"
            v-model:page="queryParams.pages.current" v-model:limit="queryParams.pages.size" /> -->
          <el-pagination size="default" @change="gpsPage" layout="prev, pager, next" :total="queryParams.pages.total"
            v-model:current-page="queryParams.pages.current" v-model:page-size="queryParams.pages.size"
            :pager-count="6" />

        </div>
      </div>
    </div>
    <div class="map-container">
      <div id="trajectoryMap" style="width: 100%; height: 100%"></div>
    </div>
    <el-dialog destroy-on-close class="dialogTableVisibleclass" v-model="outerVisible" title="设备详情">
      <div class="dialogDetails">
        <div class="list">
          <div>设备名称:</div>
          <div>{{ windowData.basicInfo.deviceName }}</div>
        </div>
        <div class="list">
          <div>设备SN:</div>
          <div>{{ windowData.basicInfo.deviceCode }}</div>
        </div>
        <div class="list">
          <div>iccid:</div>
          <div>{{ windowData.basicInfo.iccid }}</div>
        </div>
        <div class="list">
          <div>IMEI:</div>
          <div>{{ windowData.basicInfo.imei }}</div>
        </div>
        <div class="list">
          <div>模块:</div>
          <div>{{ windowData.basicInfo.module }}</div>
        </div>
        <div class="list">
          <div>软件:</div>
          <div>{{ windowData.basicInfo.softVer }}</div>
        </div>
        <div class="list">
          <div>经度:</div>
          <div>{{ windowData.locationInfo.location.x }}</div>
        </div>
        <div class="list">
          <div>纬度:</div>
          <div>{{ windowData.locationInfo.location.y }}</div>
        </div>
        <div class="list" style="width: 100%;">
          <div style="width: 15%;">详细地址:</div>
          <div>{{ windowData.locationInfo.formattedAddress }} </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="outerVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>


</template>

<script setup lang="ts">
defineOptions({
  name: "location",
  inheritAttrs: false,
});
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
// import { useRouter } from 'vue-router'

// const router = useRouter()

import { initMap } from "@/common/map";
import DeviceApi, { GPSPageQuery, locationDevice } from "@/api/device"
import LocationApi, { trajectoryReq, DeviceLocationInfoReq } from "@/api/location"

let locinput = ref()

let _AMap: any = null;
let _map: any = null;
let infoWindow: any = null;
let marker: any = null
let markers: number[] = []
let outerVisible = ref(false)
const loading = ref(false);
const maxPagerCount = ref(4)
let windowData = reactive<DeviceLocationInfoReq>(
  {
    "basicInfo": {
      "id": '',
      "deviceName": "",
      "deviceCode": "",
      "deviceTypeId": '',
      "module": "",
      "softVer": "",
      "hardVer": "",
      "imei": "",
      "iccid": ""
    },
    "locationInfo": {
      "location": {
        "x": 0,
        "y": 0,
        "type": "",
        "coordinates": [
          0,
          0
        ]
      },
      "speed": 0,
      "start": 0,
      "country": "",
      "province": "",
      "city": "",
      "district": "",
      "formattedAddress": "",
      "pdop": 0,
      "gps": 0
    }
  }
)

let deptId = ref('ALL');

/** 用户查询参数  */
const queryParams = reactive<GPSPageQuery>({
  "pages": {
    "current": 1,
    "size": 50,
    "total": 0,
    "startTime": "",
    "endTime": "",
    "orders": [
      {
        "column": "",
        "asc": true
      }
    ]
  },
  "customerId": "",
  "deviceName": undefined,
  "deviceCode": undefined,
  "deviceTypeId": undefined,
  "deviceStatus": undefined,
  "onlineStatus": undefined,
  "expireStatus": undefined,
  "isChild": undefined
});
let dataMy = reactive<locationDevice>({
  countInfo: {
    expired: 0,
    notEnable: 0,
    offline: 0,
    online: 0,
    scrap: 0,
    notExpire: 0,
    total: 0
  },
  data: {
    current: 0,
    pages: 0,
    records: [],
    size: 0,
    total: 0
  }
})

function changecommand() {
  console.log(11111);

}
/** 部门树节点 Click */
function handleNodeClick() {
  gpsPage()
}
async function setMap() {
  const { AMap, map } = await initMap("trajectoryMap");
  _AMap = AMap;
  _map = map;

}

function handleCommand(command: any) {

  switch (command) {
    case '1':
      ElMessage.warning('暂未实现该排序方式')

      break;
    case '2':
      ElMessage.warning('暂未实现该排序方式')

      break;
    case '3':
      queryParams.pages.orders[0].column = 'device_name'
      gpsPage();
      break;
    case '4':
      queryParams.pages.orders[0].column = ''
      gpsPage();
      break;
    default:

      ElMessage.warning('暂未实现该排序方式')

      break;
  }


}
/**
@date: 2024-09-11 11:39:52
查询设备分页列表
*/
function gpsPage() {
  console.log('111111111111');

  loading.value = true;
  DeviceApi.gpsPage(queryParams)
    .then((data) => {
      dataMy = data
      queryParams.pages.total = data.data.total;
      queryParams.pages.current = data.data.current;
      LocationMarker()
    })
    .finally(() => {
      loading.value = false;
    });
}
function LocationMarker() {
  if (markers.length >= 1) {
    _map.remove(markers);
    markers = []
  }
  dataMy.data.records.forEach((val, idx) => {
    var lat = val.lat
    var lng = val.lng
    if (!Number.isFinite(val.lat)) return

    if (!Number.isFinite(val.lng)) return

    marker = new _AMap.Marker({
      map: _map,
      icon: '//api.jz-iot.net/uploads/default/BmMarker1.png',
      position: [lng, lat],
      offset: new _AMap.Pixel(-13, -30)
    });
    markers.push(marker);
    marker.id = val.id;
    //鼠标点击marker弹出自定义的信息窗体
    marker.on('click', function (e: any) {
      markerClick(val.id, e)
    });
  })
}
const markerClick = async (deviceId: string, e: any) => {
  const data = await LocationApi.getDeviceLocationInfo(deviceId);
  windowData = data

  infoWindow = new _AMap.InfoWindow({
    isCustom: true,  //使用自定义窗体
    content: createInfoWindow(windowData),
    offset: new _AMap.Pixel(16, -45)
  });
  if (Array.isArray(e)) {
    infoWindow.open(_map, e);
  } else {
    infoWindow.open(_map, e.target.getPosition());

  }
};

//构建自定义信息窗体
function createInfoWindow(windowDatas: DeviceLocationInfoReq) {
  // title: any, content: any
  var title = "设备信息";
  var info = document.createElement("div");
  info.className = "custom-info input-card content-window-card";
  info.style.backgroundColor = 'white';

  //可以通过下面的方式修改自定义窗体的宽高
  info.style.width = "400px";
  // 定义顶部标题
  var top = document.createElement("div");
  var titleD = document.createElement("div");
  var closeX = document.createElement("img");
  top.className = "info-top";
  titleD.innerHTML = title;
  closeX.src = "https://webapi.amap.com/images/close2.gif";
  closeX.onclick = closeInfoWindow;

  top.appendChild(titleD);
  top.appendChild(closeX);
  info.appendChild(top);

  // 定义中部内容
  var middle = document.createElement("div");
  middle.className = "info-middle";
  // middle.innerHTML = content;
  middle.innerHTML = `
 <p>
  <span style="font-weight: bold;">
      名称:
    </span>
    <span>
      ${windowDatas.basicInfo.deviceName}
    </span>
 </p>
 <p>
  <span style="font-weight: bold;">
      SN:
    </span>
    <span>
      ${windowDatas.basicInfo.deviceCode}
    </span>
 </p>
  <p>
  <span style="font-weight: bold;">
      iccid:
    </span>
    <span>
      ${windowDatas.basicInfo.iccid}
    </span>
 </p>
  <p>
  <span style="font-weight: bold;">
      IMEI:
    </span>
    <span>
      ${windowDatas.basicInfo.imei}
    </span>
 </p>
  <p>
  <span style="font-weight: bold;">
      经度:
    </span>
    <span>
      ${windowData.locationInfo.location.x}
    </span>
 </p>
  <p>
  <span style="font-weight: bold;">
      纬度:
    </span>
    <span>
      ${windowData.locationInfo.location.y}
    </span>
 </p>

  `;

  var popBtns = document.createElement("div");
  popBtns.className = "popBtns";

  var btn1 = document.createElement("div");
  btn1.className = "btn";
  btn1.innerHTML = `详情`;
  btn1.onclick = Details;
  var btn2 = document.createElement("div");
  btn2.className = "btn";
  btn2.innerHTML = `BMS`;
  btn2.onclick = Pathbmscontrol;
  var btn3 = document.createElement("div");
  btn3.className = "btn";
  btn3.innerHTML = `轨迹`;
  btn3.onclick = Trajectory;
  btn3.setAttribute("v-hasPerm", "['location:locus']");

  popBtns.appendChild(btn1);
  popBtns.appendChild(btn2);
  popBtns.appendChild(btn3);

  // 
  middle.appendChild(popBtns);
  info.appendChild(middle);
  // 定义底部内容
  var bottom = document.createElement("div");
  bottom.className = "info-bottom";
  bottom.style.position = 'relative';
  bottom.style.top = '0px';
  bottom.style.margin = '0 auto';
  var sharp = document.createElement("img");
  sharp.src = "https://webapi.amap.com/images/sharp.png";
  bottom.appendChild(sharp);
  info.appendChild(bottom);


  return info;
}
//关闭信息窗体
function closeInfoWindow() {
  _map.clearInfoWindow();
}
function Pathbmscontrol() {
  router.push({ path: '/bmscontrol/bms', query: { deviceSN: windowData.basicInfo.deviceCode } });
}
function Trajectory() {
  router.push({ path: '/location/trajectory', query: { deviceSN: windowData.basicInfo.deviceCode, id: windowData.basicInfo.id, } });
}
function Details() {
  outerVisible.value = true
}
function menuSelect(e: string) {
  deptId.value = e
  queryParams.deviceStatus = undefined
  queryParams.onlineStatus = undefined
  queryParams.expireStatus = undefined
  if (e === 'ONLINE' || e === 'OFFLINE') {
    queryParams.onlineStatus = e
  } else if (e === 'NOT_ENABLED') {
    queryParams.deviceStatus = e
  } else if (e === 'NOT_EXPIRED' || e === 'EXPIRED') {
    queryParams.expireStatus = e
  }
  gpsPage()
}
let recordsID = ref()

function gpsData(data: any) {
  console.log(data, 'data');
  recordsID.value = data.id
  if (data.lng && data.lat) {
    _map.setZoomAndCenter(12, [data.lng, data.lat], false, 500);
    setTimeout(() => {
      markerClick(data.id, [data.lng, data.lat])
    }, 550)
  } else {
    ElMessage.warning('该设备暂无定位')
  }

}
const clientID = ref('')
/** 初始化图表1  */
onMounted(() => {
  setMap();
  setTimeout(() => {
    if (route.query.deviceID !== '' && route.query.deviceID !== undefined) {
      for (let i in dataMy.data.records) {
        if (route.query.deviceID == dataMy.data.records[i].id) {
          gpsData(dataMy.data.records[i])
        }
      }
    } else if (route.query.clientID !== '' && route.query.clientID !== undefined) {

      queryParams.customerId = route.query.clientID as string
      clientID.value = route.query.clientID as string
      console.log(queryParams, 77777);
      gpsPage()

    }
  }, 500)

  setMap();
});

</script>
<style lang="scss" scoped>
// .el-pagination button {
//   width: 8px; /* 设置按钮宽度 */
// }
#trajectoryMap :deep(.amap-info-outer) {
  color: #000000;
}

.dialogDetails {
  display: flex;
  flex-wrap: wrap;
  width: 100%;

  .list {
    display: flex;
    width: 50%;

    div {
      color: #000000;
      font-size: 16px;

      &:nth-child(1) {
        width: 30%;
      }
    }
  }
}

.locationIndexPage {
  display: flex;
  height: calc(100vh - 120px);
  box-sizing: border-box;
  padding: 10px 10px 10px 0;
  overflow: hidden;

  .menu-container {
    width: 370px;
    min-height: 480px;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .custom-wrapper {
      width: 100%;
      flex: 0 0 50%;
      min-height: 100px;
      margin: 0px;
      background: #2b2b2b;
      border-radius: 3px;
      position: relative;
      min-height: 130px;

      .titles {
        padding: 0px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        font-size: 15px;
        border-bottom: 1px solid #4d4d4d;
        color: #fff;
      }
    }

    .device-wrapper {
      margin: 0px 5px 0px 0px;
      width: 100%;
      flex: 0 0 49%;
      padding: 5px;
      box-sizing: border-box;
      overflow: hidden;
      background: #2b2b2b;
      border-radius: 3px;

      .serach {
        display: flex;
        height: 28px;
        width: 100%;
        justify-content: space-between;
        align-items: center;
      }

      .sorting {
        width: 100%;
        height: calc(100% - 28px);

        .live-title {
          display: flex;
          height: 35px;
          font-size: 14px;
          flex-wrap: wrap;
          padding-top: 5px;
          justify-content: space-around;
          margin-bottom: 2px;

          .title-item {
            text-align: center;
            line-height: 1;
            font-size: 12px;
            cursor: pointer;
            padding-top: 5px;

            &.active {
              color: #409eff;
            }

            &:hover {
              color: #409eff;
            }
          }
        }

        .myTable {
          border-collapse: collapse;
          width: 100%;
          // height: calc(100% - 35px - 32px);
          height: calc(100% - 35px - 60px);

          min-height: 100px;
          border: 1px solid #4d4d4d;
          font-size: 14px;
          color: #fff;
          overflow: auto;
          margin-bottom: 6px;

          .flexBetCenter {
            display: flex;
            line-height: 26px;
            cursor: pointer;

            &:hover {
              background: #00000078;
            }

            &.active {
              background: #00000078;

            }

            div {
              width: 50%;
              text-align: center;
            }
          }
        }
      }
    }
  }

  .map-container {
    flex: 1;
    width: calc(100% - 20px);
    min-height: 480px;
    min-width: 400px;
    position: relative;
    background: #000000;
    height: 100%;
    padding-left: 10px;
  }
}

// 复用样式
.warp {
  color: #fff;
  background: #1c1c1c;
  border-radius: 5px;
}
</style>
<style lang="scss">
.sortingLocation {
  .el-dropdown-menu.el-dropdown-menu--default {
    background-color: #fff !important;

  }
}

.dialogTableVisibleclass {
  background-color: #f1f1f1;

  .el-dialog__title {
    color: #000;
  }
}

.el-popper__arrow:before {
  background: #fff !important;
  border: 1px solid #fff !important;
}

// /* 定制滚动条整体 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  background-color: #9d9d9d;
}

/* 定制滚动条轨道 */
::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  /* 轨道颜色 */
}

/* 定制滚动条滑块 */
::-webkit-scrollbar-thumb {
  background-color: #9d9d9d;
  /* 滑块颜色 */
  border-radius: 6px;
  /* 圆角 */
}

/* 滑块在鼠标悬停时改变颜色 */
::-webkit-scrollbar-thumb:hover {
  background-color: #747373;
}




.map-container {
  #trajectoryMap {

    .content-window-card {
      position: relative;
      box-shadow: none;
      bottom: 0;
      left: 0;
      width: auto;
      padding: 0;
    }

    .content-window-card p {
      height: 2rem;
    }

    .custom-info {
      border: solid 1px silver;
    }

    div.info-top {
      position: relative;
      background: none repeat scroll 0 0 #F9F9F9;
      border-bottom: 1px solid #CCC;
      border-radius: 5px 5px 0 0;
    }

    div.info-top div {
      display: inline-block;
      color: #333333;
      font-size: 14px;
      font-weight: bold;
      line-height: 31px;
      padding: 0 10px;
    }

    div.info-top img {
      cursor: pointer;
      position: absolute;
      top: 10px;
      right: 10px;
      transition-duration: 0.25s;
    }

    div.info-top img:hover {
      box-shadow: 0px 0px 5px #000;
    }

    div.info-middle {
      padding: 0 10px 10px;

      span {
        font-size: 14px;
        line-height: 32px;
        color: #000;
      }
    }

    div.info-bottom {
      height: 0px;
      width: 100%;
      clear: both;
      text-align: center;
    }

    div.info-bottom img {
      position: relative;
      z-index: 104;
    }

    span {
      margin-left: 5px;
      font-size: 11px;
    }

    .info-middle img {
      float: left;
      margin-right: 6px;
    }

    .popBtns {
      display: flex;

      .btn {
        padding: 1px 3px;
        margin: 5px 5px 0 0;
        border: 1px solid #2ec7c9;
        border-radius: 5px;
        flex-shrink: 0;
        color: #2ec7c9;
        font-size: 14px;
        cursor: pointer;
      }
    }
  }
}
</style>
